package org.dentalcard.ui.security.tools;

import org.dentalcard.entity.DecUser;
import org.dentalcard.service.PersistenceManager;
import org.dentalcard.service.impl.DecUserDaoImpl;
import org.dentalcard.ui.main.MainFrameBuilder;
import org.dentalcard.ui.schedule.AddNewShiftPopup;
import org.dentalcard.ui.security.AddNewUserPopup;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @user: Vladimir Chernishov
 * @date: 21.12.11
 * @time: 13:50
 */
public class ButtonsPanel extends JPanel {

    private final UserTableModel model;
    private final DecUser decUser;
    private final JButton save;
    private final JButton discard;
    private final JButton delete;
    private final JButton newUser;
    
    
    public ButtonsPanel(DecUser user, UserTableModel model) {
        super(new FlowLayout());
        this.model = model;
        this.decUser = user;
        save = new JButton("Save");
        discard = new JButton("Discard");
        delete = new JButton("Delete");
        newUser = new JButton("New");
        initButtons();
        this.setMinimumSize(new Dimension(200, 20));
        this.setPreferredSize(new Dimension(200, 20));
    }

    private void initButtons() {
        save.setEnabled(false);
        save.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                PersistenceManager.saveOrUpdate(decUser);
                discard.setEnabled(false);
                save.setEnabled(false);
            }
        });

        discard.setEnabled(false);
        delete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (JOptionPane.showConfirmDialog(MainFrameBuilder.getMainFrame(), "Are you sure to delete " +
                        decUser.getName() + " User?") == JOptionPane.YES_OPTION) {
                    PersistenceManager.delete(decUser);
                    model.reload();
                }
            }
        });
        newUser.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new AddNewUserPopup(MainFrameBuilder.getMainFrame()).setVisible(true);
                model.reload();
            }
        });
        this.add(save);
        this.add(discard);
        this.add(delete);
        this.add(newUser);
    }

    public void setChanged() {
        save.setEnabled(true);
        discard.setEnabled(true);
    }
}
